<template>
  <div>
    <el-form-item
      v-if="type === 'IMPORT'"
      label="关联模型"
      prop="modelCode"
      :rules="[
        {
          required: true,
          message: '请选关联模型',
          trigger: 'change',
        },
      ]"
    >
      <tree-select
        style="width: 400px"
        :loading="modelLoading"
        v-model="value.relModelCode"
        filterable
        :fieldMap="{
          value: 'id',
          label: 'name',
          disabled: 'disabled',
        }"
        :filterNodeMethod="filterNodeMethod"
        :treeData="modelList"
        @change="loadAllFields('clear')"
      />
    </el-form-item>
    <el-form-item
      v-if="type === 'IMPORT'"
      label="导入字段:"
      prop="filterFields"
      :rules="[
        {
          required: true,
          message: '请选择导入字段',
          trigger: 'change',
        },
      ]"
    >
      <el-select
        multiple
        :loading="subLoading"
        v-model="value.filterFields"
        placeholder="请选择"
        style="width: 500px"
      >
        <el-option
          v-for="item in fieldList"
          :key="item.id"
          :value="item.code"
          :label="item.name + '(' + item.code + ')'"
        ></el-option>
      </el-select>
    </el-form-item>
    <el-form-item v-if="type === 'IMPORT'" label="导入字段格式:">
      <div>请以“#”作为分隔符连接所选字段。</div>
      <div>例：{{ example }}</div>
    </el-form-item>
  </div>
</template>
<script>
import LabelExpression from "@/components/LabelExpression"
import { filterNodeMethod } from "@/utils/treeSelectFormat"
import { getHmmodelfolderListTree } from "@/apis/paas/HmModelFolderController.js"
import { getHmentitymodelList } from "@/apis/paas/HmEntityModelController.js"
import lodash from "lodash"

//关联主键字段 可选择的字段类型
const NOT_SELECT_TYPE_RELATION_PRIMARY_KEY = [
  "SHORT_TEXT",
  "PARENT_ID",
  "TIME",
  "SEQ",
  "NUMBER",
  "LONG_TEXT",
  "DATE",
  "INTEGER",
  "BOOL",
]
export default {
  name: "RelationConfig",
  props: {
    value: {
      type: Object,
      default: () => {
        return {}
      },
    },
    type: {
      type: String,
      default: "",
    },
    modelId: {
      type: Number | String,
      default: "",
    },
  },
  components: {
    LabelExpression,
  },
  computed: {
    example() {
      let str = ""
      this.value.filterFields.forEach((i) => {
        let c = this.fieldList.find((item) => item.code === i)
        if (c) {
          str += `${c.name}#`
        }
      })
      return str.substring(0, str.length - 1)
    },
  },
  data() {
    return {
      filterNodeMethod,
      modelList: [],
      fieldList: [],
      modelLoading: false,
      subLoading: false,
    }
  },
  created() {
    this.loadModelList()
    if (!!this.value.relModelCode) {
      this.loadAllFields()
    }
  },
  methods: {
    // 获取所有业务模型
    loadModelList() {
      this.modelLoading = true
      getHmmodelfolderListTree({
        modelTypes: "ENTITY",
      })
        .then((res) => {
          res.forEach((node) => {
            node.type = "folder"
          })
          this.modelList = this.createModelTreeNode(res || [], this.modelId)
        })
        .finally(() => {
          this.modelLoading = false
        })
    },
    createModelTreeNode(tree, idDisabled = "") {
      return lodash.cloneDeep(tree).map((node) => {
        node.disabled = node.type === "folder"
        if (node.modelResults) {
          node.id = "folder" + node.id
          node.children = node.modelResults || []
          node.children.forEach((item) => {
            item.disabled = item.id == idDisabled
            item._id = item.id
            item.id = item.code
            item.name = `${item.name}（${item.code}）`
          })
        }
        return node
      })
    },
    loadAllFields(flag) {
      this.subLoading = true
      getHmentitymodelList({
        modelKey: this.value.relModelCode,
        activated: true,
      })
        .then((res) => {
          this.fieldList = res.filter((item) => item.status !== "SCRIPT")
          this.fieldList = this.fieldList
            .filter(
              (i) =>
                (i.createType !== "SYSTEM" || i.code === "id") &&
                NOT_SELECT_TYPE_RELATION_PRIMARY_KEY.includes(i.type)
            )
            .map((i) => {
              return {
                ...i,
                value: i.code,
                label: i.name,
              }
            })
          if (flag === "clear") {
            this.$set(this.value, "filterFields", [])
          }
        })
        .finally(() => {
          this.subLoading = false
        })
    },
  },
}
</script>
